package com.sxkf.template.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sxkf.core.api.vo.R;
import com.sxkf.template.constants.ViewTypeConstants;
import com.sxkf.template.entity.*;
import com.sxkf.template.mapper.PostMapper;
import com.sxkf.template.service.*;
import io.swagger.annotations.*;
import org.jeecg.common.util.CheckEmptyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户帖子 前端控制器
 * </p>
 *
 * @author 杨玉龙
 * @since 2024-08-20 11:48:57
 */
@Api(tags = "动态（帖子）")
@RestController
@RequestMapping("/post")
public class PostController {
    @Resource
    private PostService postService;
    @Resource
    private PostMapper postMapper;

    @Resource
    private TopicService topicService;

    @Resource
    private UserService userService;

    @Resource
    private ProductViewService productViewService;

    @Resource
    private PostLikeService postLikeService;
    @Resource
    private PostCollectService postCollectService;
    @Autowired
    private UserLikeService userLikeService;
    @Autowired
    private UnlockPostService unlockPostService;


    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "当查询动态时（1=推荐，2=关注,3=附近，4-在线），当查询互助赚时（1=距离最近，2=最新发布）"),
            @ApiImplicitParam(name = "postType", value = "1=互助赚，2=动态")
    })
    @ApiOperation(value = "分页查询帖子",notes = "互助赚&&动态")
    @GetMapping(value = "/page")
    public R<IPage<Post>> page(@RequestParam Integer pageNo,
                               @RequestParam Integer pageSize,
                               @RequestParam String userId,
                               @RequestParam String type,
                               @RequestParam String postType,
                               @RequestParam(required = false) String topicId,
                               @ApiParam("标题")
                                   @RequestParam(required = false) String postTitle,
                               @ApiParam("经度")
                                   @RequestParam(required = false) Double longitude,
                               @ApiParam("纬度")
                                   @RequestParam(required = false) Double latitude) {
        IPage<Post> result = postService.pagePost(pageNo, pageSize, userId, type,postType,topicId,postTitle,longitude,latitude);
        List<Post> records = result.getRecords();
        if (records.isEmpty()){
            return R.success(result);
        }
        List<String> topicIdList = new ArrayList<>();
        records.forEach(record -> {
            topicIdList.add(record.getTopicId());
        });
        List<Topic> topicList = topicService.list(new LambdaQueryWrapper<Topic>()
                .in(Topic::getId, topicIdList));
        Map<String, String> topicTitleMap = topicList.stream().collect(Collectors.toMap(Topic::getId, Topic::getTitle));

        // 帖子 点赞
        List<PostLike> likeList = postLikeService.list(new LambdaQueryWrapper<PostLike>()
                .eq(PostLike::getUserId, userId));
        List<String> likePostIdList = likeList.stream().map(PostLike::getPostId).collect(Collectors.toList());


        // 帖子 收藏
        List<PostCollect> collectList = postCollectService.list(new LambdaQueryWrapper<PostCollect>()
                .eq(PostCollect::getUserId, userId));
        List<String> collectPostIdList = collectList.stream().map(PostCollect::getPostId).collect(Collectors.toList());

        records.forEach(record -> {
            record.setTopicTitle(topicTitleMap.get(record.getTopicId()));
            if (likePostIdList.contains(record.getId())){
                record.setIsLikePost(1);
            }else {
                record.setIsLikePost(0);
            }
            if (collectPostIdList.contains(record.getId())){
                record.setIsCollectPost(1);
            }else {
                record.setIsCollectPost(0);
            }
        });
        result.setRecords(records);
        return R.success(result);
    }

//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "type", value = "当查询互助赚时（3=距离最近，1=最新发布）"),
//            @ApiImplicitParam(name = "postType", value = "互动赚(1=闲置物品，2=维修业务，3=家政服务，4=求职信息，5=代驾服务，6=求职信息，7=废品回收，8=搬家服务)")
//    })
    @ApiOperation(value = "分页查询互动赚帖子",notes = "互助赚&&动态")
    @GetMapping(value = "/interPage")
    public R<IPage<Post>> interactionPage(@RequestParam Integer pageNo,
                               @RequestParam Integer pageSize,
                               @RequestParam String userId,
                               @ApiParam("帖子标题")
                               @RequestParam(required = false) String postTitle,
                               @ApiParam("1=距离最近，2=最新发布")
                               @RequestParam(required = false) String type,
                               @ApiParam("城市")
                               @RequestParam(required = false) String address,
                               @ApiParam("话题id")
                               @RequestParam(required = false) String topicId,
                                          @ApiParam("经度")
                                          @RequestParam(required = false) Double longitude,
                                          @ApiParam("纬度")
                                          @RequestParam(required = false) Double latitude) {

        IPage<Post> result = postService.interactionPage(pageNo,pageSize,userId,postTitle,type,address,topicId,longitude,latitude);
        List<Post> records = result.getRecords();
        if (records.isEmpty()){
            return R.success(result);
        }
        List<String> topicIdList = new ArrayList<>();
        records.forEach(record -> {
            topicIdList.add(record.getTopicId());
        });
        List<Topic> topicList = topicService.list(new LambdaQueryWrapper<Topic>()
                .in(Topic::getId, topicIdList));
        Map<String, String> topicTitleMap = topicList.stream().collect(Collectors.toMap(Topic::getId, Topic::getTitle));

        // 帖子 点赞
        List<PostLike> likeList = postLikeService.list(new LambdaQueryWrapper<PostLike>()
                .eq(PostLike::getUserId, userId));
        List<String> likePostIdList = likeList.stream().map(PostLike::getPostId).collect(Collectors.toList());


        // 帖子 收藏
        List<PostCollect> collectList = postCollectService.list(new LambdaQueryWrapper<PostCollect>()
                .eq(PostCollect::getUserId, userId));
        List<String> collectPostIdList = collectList.stream().map(PostCollect::getPostId).collect(Collectors.toList());

        records.forEach(record -> {
            record.setTopicTitle(topicTitleMap.get(record.getTopicId()));
            if (likePostIdList.contains(record.getId())){
                record.setIsLikePost(1);
            }else {
                record.setIsLikePost(0);
            }
            if (collectPostIdList.contains(record.getId())){
                record.setIsCollectPost(1);
            }else {
                record.setIsCollectPost(0);
            }
        });
        result.setRecords(records);
        return R.success(result);
    }

    @ApiOperation(value = "查一个动态")
    @GetMapping(value = "/one")
    public R<Post> one(@RequestParam String postId,@RequestParam String userId) {
        Post post = postService.getById(postId);

        if (CheckEmptyUtil.isEmpty(post)){
            return R.success(post);
        }

        Topic topic = topicService.getOne(new LambdaQueryWrapper<Topic>()
                .eq(Topic::getId, post.getTopicId()));
        if (!CheckEmptyUtil.isEmpty(topic)){
            post.setTopicTitle(topic.getTitle());
        }

        // 帖子 点赞
        PostLike postLike = postLikeService.getOne(new LambdaQueryWrapper<PostLike>()
                .eq(PostLike::getPostId, postId)
                .eq(PostLike::getUserId, userId));
        // 帖子 收藏
        PostCollect postCollect = postCollectService.getOne(new LambdaQueryWrapper<PostCollect>()
                .eq(PostCollect::getPostId, postId)
                .eq(PostCollect::getUserId, userId));

        UserLike userLike = userLikeService.getOne(new LambdaQueryWrapper<UserLike>()
                .eq(UserLike::getUserId, userId)
                .eq(UserLike::getLikeUserId, post.getUserId())
        );

        UnlockPost unlockPost = unlockPostService.getOne(new LambdaQueryWrapper<UnlockPost>()
                .eq(UnlockPost::getPostId, postId)
                .eq(UnlockPost::getUserId, userId)
        );
        // 是否解锁
        post.setIsUnlock(!CheckEmptyUtil.isEmpty(unlockPost) && unlockPost.getState().equals("1") || post.getUserId().equals(userId));
        if (CheckEmptyUtil.isEmpty(postLike)){
            post.setIsLikePost(0);
        }else {
            post.setIsLikePost(1);
        }
        if (CheckEmptyUtil.isEmpty(postCollect)){
            post.setIsCollectPost(0);
        }else {
            post.setIsCollectPost(1);
        }
        if (CheckEmptyUtil.isEmpty(userLike)){
            post.setIsLikeUser(0);
        }else {
            post.setIsLikeUser(1);
        }
        User user = userService.getById(post.getUserId());
        post.setNickName(user.getNickName());
        post.setAvatar(user.getAvatar());

        return R.success(post);
    }


    @ApiOperation(value = "添加动态")
    @PostMapping(value = "/add")
    public R<?> add(@RequestBody Post post) {

//        if (CheckEmptyUtil.isEmpty(post.getDisableViewIds())){
//            post.setDisableViewIds(null);
//        }
//        if (CheckEmptyUtil.isEmpty(post.getEnableViewIds())){
//            post.setEnableViewIds(null);
//        }
        postService.add(post);
        return R.success();
    }

    @ApiOperation(value = "删除动态")
    @GetMapping(value = "/id")
    public R<?> delete(@RequestParam String id) {
        postService.removeById(id);
        return R.success();
    }

    @ApiOperation(value = "分享帖子")
    @GetMapping(value = "/share")
    public R<?> share(@RequestParam String id) {
        postMapper.addShareCount(id);
        return R.success();
    }

    @ApiOperation(value = "帖子足迹")
    @GetMapping("/addUserView")
    public R<?> addUserView(@ApiParam("帖子id") @RequestParam String id,
                        @ApiParam("用户id") @RequestParam String userId) {
        // 看详情留足迹，添加足迹
        Post post = postService.getById(id);
        String viewType = "";
        if (!CheckEmptyUtil.isEmpty(post)){
            if (post.getType().equals("1")){
                viewType = ViewTypeConstants.POST_1;
            }else if (post.getType().equals("2")){
                viewType = ViewTypeConstants.POST_2;
            }
        }else {
            return R.success();
        }

        // 加足迹
        if (CheckEmptyUtil.isNotEmpty(userId)){
            long count = productViewService.count(new LambdaQueryWrapper<ProductView>()
                    .eq(ProductView::getUserId, userId)
                    .eq(ProductView::getViewId, id)
                    .eq(ProductView::getViewType, viewType));
            if (count == 0){
                User user = userService.getById(userId);
                ProductView productView = new ProductView();
                productView.setViewId(id);
                productView.setViewType(viewType);
                productView.setUserId(userId);
                productView.setUserNickName(user.getNickName());
                productView.setUserAvatar(user.getAvatar());
                productViewService.save(productView);
            }

            //浏览量+1
            postMapper.addViewCount(id);
        }

        return R.success();
    }

    @ApiOperation(value = "查询自己的帖子")
    @GetMapping(value = "/self")
    public R<IPage<Post>> pageSelfPost(@RequestParam Integer pageNo,
                                       @RequestParam Integer pageSize,
                                       @RequestParam String userId) {
        return R.success(postService.self(pageNo,pageSize,userId));
    }

    @ApiOperation(value = "查询自己的互动赚帖子")
    @GetMapping(value = "/selfInter")
    public R<IPage<Post>> pageSelfInterPost(@RequestParam Integer pageNo,
                                            @RequestParam Integer pageSize,
                                            @RequestParam String userId) {
        return R.success(postService.pageSelfInterPost(pageNo,pageSize,userId));
    }

}
